package cn.tedu.ivos2.base.file;

import cn.tedu.ivos2.base.response.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@Slf4j
@RestController
@RequestMapping("/v1/file")
public class UploadController {
    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf('.'));
        filename = UUID.randomUUID()+suffix;
        String dirPath = "d:/files";
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        File dirFile = new File(dirPath+datePath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath = dirPath+datePath+filename;
        file.transferTo(new File(filePath));
        return JsonResult.ok(datePath+filename);
    }

    @PostMapping("remove")
    public JsonResult remove(String imgUrl){
        log.debug("删除图片业务：imgUrl={}", imgUrl);
        //拼接完整的路径,创建对应的java对象,删除磁盘上此路径对应的图片文件
        new File("d:/files"+imgUrl).delete();
        return JsonResult.ok();
    }
}
